import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import moduleName from "../../../modules/Ueditor";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage } from "umi-plugin-react/locale";
import Editor from "@/utils/Editor";
import { routerRedux } from "dva/router";
import BackRouter from "../../robotManagement/backRouter";
import { Row, Col, Card, Icon, Tooltip, Form, Input, Button, Select, Modal, message, Tabs, Checkbox, Table } from "antd";
import styles from "./index.less";
import UserSession from "@/UserSession";
import AnswerUtils from "@/utils/answerUtils/answerUtils";
import jsonDataUtils from "@/utils/jsonDataUtils";
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
const TabPane = Tabs.TabPane;
@connect(({ process, loading }) => ({
	process,
	loading: loading.effects["antistopReply/fetch"],
}))
class editText extends Component {
	constructor(props) {
		super(props);
		const { keywordId, id, urlPrefix } = this.props.match.params;
		this.state = {
			list: [],
			total: "",
			showModelA: false,
			dataSource: [],
			name: "",
			data: {},
			dictId: "",
			content: "",
			type: 1,
			keywordId,
			id,
			urlPrefix,
			// areatext:''
			entityCurrent: 1,
			entityTotal: 0,
			entityLoading: false,
			isSystem: true,
			detail: null,
		};
	}

	componentDidMount() {
		// this.getAllRobot();
		const { keywordId } = this.state;
		const { dispatch, currentUser } = this.props;
		dispatch({
			type: "antistopReply/fetchDetail",
			payload: { id: keywordId },
			callback: (res) => {
				this.setState({
					detail: res,
					isSystem: res.answerSource && res.answerSource == 1 ? false : true,
					name: res.modelName,
					dictId: res.modelId,
					keywordId,
				}, () => {
					//处理答案字段
					let answerObj = {
						isDefault: true,
						content: res.answer,
						id: keywordId,
						slotValues: [],
						userTagIdList: [],
						contentType: res.type + "",    //答案内容类型 0=纯文本类型, 1=富文本类型, 2=跳转卡片 默认为0
					}

					if (jsonDataUtils.isJsonString(res.answer)) {
						answerObj.cardVo = JSON.parse(res.answer)
					}
					setTimeout(() => {
						this.AnswerUtils.setAnswers(answerObj)
					}, 300)
				});
			},
		});
	}

	getCustomEntity = () => {
		const { dispatch, currentUser } = this.props;
		const { entityCurrent } = this.state;
		const formInfo = this.props.form.getFieldsValue()
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "antistopReply/fetche",
				payload: { current: entityCurrent, size: 10, search: formInfo.query, isEnum: 1 },
				callback: (res) => {
					this.setState({
						dataSource: res.records,
						entityLoading: false,
						entityTotal: res.total
					});
				},
			});
		});
	}

	getSysEntity = () => {
		const { dispatch, currentUser } = this.props;
		const { entityCurrent } = this.state;
		const formInfo = this.props.form.getFieldsValue()
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customDictionary/fetch",
				payload: {
					current: entityCurrent,
					size: 10,
					search: formInfo.query,
					urlPrefix: 'headquarters',
					isEnum: 1
				},
				callback: (res) => {
					this.setState({
						dataSource: res.records,
						entityLoading: false,
						entityTotal: res.total
					})
				},
			});
		});
	}

	getModelList = () => {
		const { dispatch, currentUser } = this.props;
		this.setState({ entityLoading: true }, () => {
			const formInfo = this.props.form.getFieldsValue()
			console.log(formInfo);
			// if (formInfo.type == 0) {
			this.getCustomEntity()
			// } else {
			// 	this.getSysEntity()
			// }
		})
	};

	handleDeletes = () => {
		this.getModelList();
		this.setState({ showModelA: true });
	};

	handleChange = (value) => {
		console.log(value);
		this.setState({ dictId: value.key, name: value.label, });
	};

	knowBase = (row) => {
		this.setState({ showModelA: false, showButton: false, dictId: row.id, name: row.name });
	};

	save() {
		const { urlPrefix, isSystem, content } = this.state;
		this.addapi(urlPrefix === 'headquarters' && isSystem ? content : this.ueditor.getUeditorContent(), 1);
	}

	saveTextArea = () => {
		const { urlPrefix, isSystem, content, value } = this.state;
		this.addapi(urlPrefix === 'headquarters' && isSystem ? content : value, 2);
	};

	textAreaid = (e) => {
		this.setState({ value: e.target.value });
	};

	addapi = (val, type) => {
		// fetchc'
		const { dictId, isSystem, name } = this.state;
		if (dictId && name) {
			const { dispatch, currentUser } = this.props;
			this.reqRef = requestAnimationFrame(() => {
				dispatch({
					type: "antistopReply/fetchb",
					payload: { modelId: dictId, answer: val, id: this.state.keywordId, type, answerSource: isSystem ? 0 : 1, rootCategoryId: this.state.id, },
					callback: (res) => {
						if (typeof res.code !== 'undefined' && res.code !== 0) {
							// message["error"](`${res.message}`);
						} else {
							message["info"](`${res.message}`);
							setTimeout(() => {
								dispatch(routerRedux.push({ pathname: `/knowledgeDesign/myKnowledge/${this.state.id}/keywordReply`, }));
							}, 1000);
						}
					},
				});
			});
		} else {
			message["error"]("实体名称不能为空");
		}
	};

	onTabChange = (e) => {
		this.setState({
			type: e,
		});
	};

	jumpDictionaryPage = () => {
		const w = window.open("about:blank");
		w.location.href = "/knowledgeDesign/customDictionary";
		this.setState({ showModelA: false });
	};

	onSubmit = async () => {
		const answerResult = await this.AnswerUtils.getAnswerResult();
		if (answerResult.flag) {
			let answer = answerResult.result.content;
			let contentType = answerResult.result.contentType;
			this.addapi(answer, contentType);
		} else {
			if (answerResult.message) {
				message.error(answerResult.message)
			};
			return false;
		}
	};

	queryEntity = current => {
		this.setState({ entityCurrent: current }, () => {
			this.getModelList()
		})
	}

	render() {
		const { getFieldDecorator } = this.props.form;
		const { content, type, urlPrefix, dataSource, entityCurrent, entityLoading, entityTotal, dictId, isSystem, detail } = this.state;
		const FormItemLayont = {
			labelCol: {
				xs: 24,
				sm: 4,
				md: 3,
			},
			wrapperCol: {
				xs: 24,
				sm: 20,
				md: 21,
			},
		};
		const tailFormItemLayout = {
			wrapperCol: {
				xs: {
					span: 24,
					offset: 0,
				},
				sm: {
					span: 20,
					offset: 4,
				},
				md: {
					span: 21,
					offset: 3,
				}
			},
		};
		const columns = [
			{
				title: '实体名称',
				dataIndex: 'name'
			},
			{
				title: '操作',
				width: 100,
				render: (text, row) => {
					return dictId && row.id === dictId ? <Button disabled size="small">已选择</Button> : <Button size="small" type="primary" onClick={() => this.knowBase(row)}>选择</Button>
				}
			}
		];

		return (
			<Suspense fallback={<PageLoading />}>
				<PageHeaderWrapper>
					<div className={styles.backgroundp}>
						<Row className={styles.colorBackground}>
							<Col style={{ padding: 10, color: "#4B5475", fontWeight: 600 }} xs={24}>
								<div className={styles.title}>
									<FormattedMessage id='app.antistopReply.editAntistopRevert' />
								</div>
							</Col>
							<div style={{ position: "absolute", right: 20, top: 16, zIndex: 2 }}>
								<BackRouter pathname={`/knowledgeDesign/myKnowledge/${this.state.id}/keywordReply`}></BackRouter>
							</div>
						</Row>
						<Card style={{ zIndex: 1 }} bordered={false}>
							<Form layout='horizontal'>
								<FormItem label='关键词实体' {...FormItemLayont} style={{ display: 'flex', alignItems: 'center', }}>
									<div style={{ display: 'flex', alignItems: 'center', }}>
										<span className={styles.configuration}>{this.state.name}</span>{" "}
										{urlPrefix ? '' : (
											<span className={styles.buttong2} style={{ top: 0 }} onClick={this.handleDeletes}>
												<span>{" "}<Icon type='edit' style={{ marginRight: 5 }} /></span>
												<span><FormattedMessage id='app.antistopReply.change' /></span>
											</span>
										)}
									</div>
								</FormItem>
								<FormItem label='关键词回复' {...FormItemLayont}>
									<AnswerUtils onRef={ref => this.AnswerUtils = ref} form={this.props.form} />
								</FormItem>
								<FormItem {...tailFormItemLayout}>
									<Button type={"primary"} onClick={this.onSubmit}>保存</Button>
								</FormItem>
							</Form>
						</Card>

						<Modal
							className='modelZdy'
							width={600}
							footer={null}
							title='添加/更换实体'
							visible={this.state.showModelA}
							okText={<FormattedMessage id='app.customDictionary.save' />}
							cancelText={<FormattedMessage id='app.customDictionary.cancel' />}
							onCancel={() => {
								this.setState({ showModelA: false });
							}}
							onOk={this.businessWayA} // 确定方法开出去
						>
							<Form layout="inline" style={{ marginBottom: 20 }}>
								{/* <FormItem>
									{
										getFieldDecorator('type', { initialValue: 0 })(
											<Select style={{ width: 110 }} onChange={() => this.queryEntity(1)}>
												<Select.Option value={0}>自定义实体</Select.Option>
												{
													UserSession.isAdmin() ? '' : <Select.Option value={1}>系统实体</Select.Option>
												}
											</Select>
										)
									}
								</FormItem> */}
								<FormItem>
									{getFieldDecorator('query')(<Input placeholder="请输入实体名称" />)}
								</FormItem>
								<FormItem>
									<Button type="primary" onClick={() => this.queryEntity(1)}>查询</Button>
								</FormItem>
								<FormItem>
									<Button type='primary' onClick={this.jumpDictionaryPage}>添加实体</Button>
								</FormItem>
							</Form>

							<Table
								rowKey={'id'}
								columns={columns}
								loading={entityLoading}
								dataSource={dataSource}
								pagination={{
									total: entityTotal,
									current: entityCurrent,
									onChange: this.queryEntity
								}}
							/>
							<div style={{ height: 20 }} />
						</Modal>
					</div>
				</PageHeaderWrapper>
			</Suspense>
		);
	}
}

export default connect(({ user }) => ({
	// 全局数据
	currentUser: user.currentUser,
}))(Form.create()(editText));
